<script lang="ts" setup>
import { onMounted, ref, reactive, nextTick } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElTree,
  ElButton,
  ElTable,
  ElSwitch,
  ElPagination,
  ElMessageBox,
  ElMessage,
  ElTooltip,
} from "element-plus";
import { Plus } from "@vben/icons";
import addEdit from "./addEdit.vue";
import { userList, edit, deleteId } from "#/api/sys/user";
import { getOrganizationsByUserId } from "#/api/sys/organization";
import { useDebounceFn } from "@vueuse/core";

const defaultProps = {
  children: "children",
  label: "organizationName",
};
const treeData = ref([]);
// 从localstorage中获取用户信息
const userInfo = JSON.parse(localStorage.getItem("userInfo"));
const userId = userInfo.id;
const treeRef = ref();

const ruleFormRef = ref();
const ruleForm = reactive<RuleForm>({
  userName: "",
  realName: "",
  phone: "",
  status: "",
  organizationId: "",
});
const rules = reactive({});
const statusOptions = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "1",
    label: "正常",
  },
  {
    value: "2",
    label: "禁用",
  },
];

const spaceInput = (field: keyof RuleForm, value: string) => {
  // 过滤空格
  if (ruleForm && field in ruleForm) {
    ruleForm[field] = value.replace(/\s+/g, "");
  }
};

const processUserData = (records: UserItem[]) => {
  return records.map((item) => ({
    ...item,
    status: String(item.status),
  }));
};

const handleNodeClick = async (e: { id: string }, node, component) => {
  ruleForm.organizationId = e.id;

  // 设置树节点的当前选中状态
  treeRef.value.setCurrentKey(e.id);

  // 1无权限 0有权限
  if (e.parentFlag == 1) {
    ElMessage.warning("没有权限访问，请联系管理员");
    tableData.value = [];
    total.value = 0;
  } else {
    try {
      const params = {
        organizationId: e.id,
      };
      const { data } = await userList(params);
      tableData.value = processUserData(data.records);
      total.value = data.total;
    } catch (error) {
      ElMessage.error("获取用户列表失败");
      console.error(error);
    }
  }
};

const search = async () => {
  try {
    const params = {
      userName: ruleForm.userName,
      realName: ruleForm.realName,
      status: ruleForm.status,
      mobile: ruleForm.phone,
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      organizationId: ruleForm.organizationId,
    };

    const { data } = await userList(params);
    if (data.records.length > 0) {
      tableData.value = processUserData(data.records);
      total.value = data.total;

      // 如果有选中的组织ID，设置树节点的选中状态
      if (ruleForm.organizationId) {
        nextTick(() => {
          treeRef.value?.setCurrentKey(ruleForm.organizationId);
        });
      }
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error("查询失败");
    console.error(error);
  }
};

const debouncedSearch = useDebounceFn(search, 500);

const resetForm = (formEl) => {
  formEl.resetFields();
  // 不需要重置选中的左侧组织ID
  // ruleForm.organizationId = "";
  currentPage.value = 1;
  search();
};

const dialogVisible = ref();
const addItem = () => {
  dialogVisible.value.addDialog();
};

const tableData = ref([]);
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);

const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();
};
const editItem = (row) => {
  dialogVisible.value.editDialog(row);
};

const delItem = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除账号【${row.userName}】吗？`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              await deleteId(row.id);
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      // 非取消操作才报错
      ElMessage.error(`删除失败: ${error.message || "未知错误"}`);
      console.error("删除账号失败:", error);
    }
  }
};

const updateStatus = async (row) => {
  const newStatus = row.status === "1" ? "2" : "1";
  if (row.status === "2") {
    try {
      await ElMessageBox.confirm("是否确认关闭？", "关闭确认", {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      });
    } catch (error) {
      row.status = newStatus;
      return;
    }
  }

  const params = {
    id: row.id,
    status: row.status,
  };

  try {
    const { code, msg } = await edit(params);
    if (code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      row.status = newStatus;
      ElMessage({
        type: "error",
        message: msg,
      });
    }
  } catch (error) {
    row.status = newStatus;
    ElMessage({
      type: "error",
      message: error,
    });
    console.error("状态修改失败:", error);
  }
};

const getTreeData = async () => {
  try {
    const { data } = await getOrganizationsByUserId();
    treeData.value = data;

    // 在获取到树数据后，如果有默认选中的组织ID，设置选中状态
    if (ruleForm.organizationId) {
      nextTick(() => {
        treeRef.value?.setCurrentKey(ruleForm.organizationId);
      });
    } else if (data && data.length > 0) {
      // 如果没有选中的组织ID，默认选中第一个根节点
      nextTick(() => {
        const firstNode = data[0];
        const firstNodeId = firstNode.id;
        treeRef.value?.setCurrentKey(firstNodeId);
        // 同时触发点击事件加载对应的数据
        ruleForm.organizationId = firstNodeId;

        // 根据parentFlag判断是否有权限：1无权限 0有权限
        if (firstNode.parentFlag == 1) {
          ElMessage.warning("没有权限访问，请联系管理员");
          tableData.value = [];
          total.value = 0;
        } else {
          search();
        }
      });
    }
  } catch (error) {
    ElMessage.error("获取组织架构失败");
    console.error(error);
  }
};

onMounted(() => {
  // search();
  getTreeData();
});
</script>
<template>
  <div class="page pageStyle">
    <div class="flex flex-col lg:flex-row">
      <div class="mr-4 w-full lg:w-1/6" style="background: #fff">
        <div class="leftTree">
          <h2>组织架构</h2>
          <ElTree
            ref="treeRef"
            :data="treeData"
            :props="defaultProps"
            node-key="id"
            @node-click="handleNodeClick"
            default-expand-all
            :expand-on-click-node="false"
            :highlight-current="true"
          >
            <template #default="{ node, data }">
              <ElTooltip
                :content="node.label"
                :disabled="!node.label || node.label.length <= 10"
                placement="top"
                :show-after="800"
              >
                <span class="tree-node-custom">
                  {{ node.label }}
                </span>
              </ElTooltip>
            </template>
          </ElTree>
        </div>
      </div>
      <div class="w-full lg:w-5/6">
        <div class="search">
          <ElForm
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            :inline="true"
            label-width="auto"
          >
            <ElFormItem label="账号：" prop="userName">
              <ElInput
                v-model="ruleForm.userName"
                placeholder="请输入账号"
                @input="(value) => spaceInput('userName', value)"
              />
            </ElFormItem>
            <ElFormItem label="姓名：" prop="realName">
              <ElInput
                v-model="ruleForm.realName"
                placeholder="请输入姓名"
                @input="(value) => spaceInput('realName', value)"
              />
            </ElFormItem>
            <ElFormItem label="手机号：" prop="phone">
              <ElInput
                v-model="ruleForm.phone"
                placeholder="请输入手机号"
                @input="(value) => spaceInput('phone', value)"
              />
            </ElFormItem>
            <ElFormItem label="状态：" prop="status">
              <ElSelect
                v-model="ruleForm.status"
                style="width: 180px"
                placeholder="请选择状态"
                @change="search()"
              >
                <ElOption
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem>
              <ElButton type="primary" @click="debouncedSearch">
                查询
              </ElButton>
              <ElButton @click="resetForm(ruleFormRef)">重置</ElButton>
            </ElFormItem>
            <ElFormItem class="addRight">
              <ElButton type="primary" @click="addItem">添加</ElButton>
            </ElFormItem>
          </ElForm>
        </div>
        <div class="table w-full">
          <ElTable :data="tableData" stripe row-key="id">
            <ElTable.TableColumn prop="userName" label="账号" align="center" />
            <ElTable.TableColumn prop="realName" label="姓名" align="center" />
            <ElTable.TableColumn prop="roleName" label="角色" align="center" />
            <ElTable.TableColumn prop="mobile" label="手机号" align="center" />
            <ElTable.TableColumn
              prop="createTime"
              label="创建时间"
              align="center"
            />
            <ElTable.TableColumn
              prop="status"
              label="状态"
              align="center"
              width="80"
            >
              <template #default="scope">
                <ElSwitch
                  v-model="scope.row.status"
                  @click.native.prevent="
                    userId !== scope.row.id &&
                      scope.row.realName !== '超级管理员' &&
                      updateStatus(scope.row)
                  "
                  style="
                    --el-switch-on-color: #2f69eb;
                    --el-switch-off-color: #c0c4cc;
                  "
                  active-value="1"
                  inactive-value="2"
                  :disabled="
                    userId == scope.row.id || scope.row.realName == '超级管理员'
                  "
                />
              </template>
            </ElTable.TableColumn>
            <ElTable.TableColumn fixed="right" label="操作" align="center">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="editItem(scope.row)"
                  :disabled="
                    userId == scope.row.id || scope.row.realName == '超级管理员'
                  "
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="delItem(scope.row)"
                  :disabled="
                    userId == scope.row.id || scope.row.realName == '超级管理员'
                  "
                  >删除</el-button
                >
              </template>
            </ElTable.TableColumn>
          </ElTable>
          <div class="pagination">
            <ElPagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 80, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    <addEdit ref="dialogVisible" @search="search"></addEdit>
  </div>
</template>
<style lang="css" scoped>
.leftTree {
  padding: 20px;
}

.el-tree {
  height: calc(100vh - 170px);
  overflow: scroll;
}

h2 {
  margin-bottom: 20px;
  font-weight: 900;
}

.search {
  padding: 20px;
  margin-top: 8px;
  background: #fff;
  padding-bottom: 0px;
}

.addRight {
  float: right;
}

.table {
  height: calc(100vh - 246px);
  padding: 0px 24px 20px 16px;
  overflow: scroll;
  background: #fff;
}

.el-table--fit {
  height: calc(100vh - 292px);
}

/* 1440px屏幕适配 */
@media screen and (max-width: 1500px) {
  .table {
    height: calc(100vh - 246px);
  }

  .el-table--fit {
    height: calc(100vh - 292px);
  }
}

/* 1920px屏幕适配 */
@media screen and (min-width: 1920px) {
  .table {
    height: calc(100vh - 200px);
  }

  .el-table--fit {
    height: calc(100vh - 240px);
  }
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px;
  padding-bottom: 0;
}

.my-message-box :deep(.el-message-box__status.el-message-box-icon--warning) {
  font-size: 30px !important;
  color: red !important;
}

:deep(.my-message-box .el-message-box__title) {
  margin: 0 20px !important;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.el-form--inline .el-form-item {
  margin-right: 10px;
}

:deep(.el-tree-node__label) {
  width: 100%;
}

.tree-node-custom {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

:deep(.el-tree-node__content) {
  overflow: hidden;
  padding-right: 8px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #2f69eb !important;
  color: white;
}

:deep(.el-tree-node.is-current > .el-tree-node__content .tree-node-custom) {
  color: white;
}

.lg\:w-5\/6 {
  background: #fff;
}
</style>